package com.tdkj.task;

import java.math.BigInteger;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.Table;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tdkj.model.shop.BeanCreditRating;
import com.tdkj.model.shop.BeanShop;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.shop.IBeanCreditRatingService;

public class CreditRatingLevelTask {
    private static final Logger logger = LoggerFactory.getLogger(CreditRatingLevelTask.class);
    
    private IBeanCreditRatingService creditRatingService;
 
    @Resource
	public void setCreditRatingService(IBeanCreditRatingService creditRatingService) {
		this.creditRatingService = creditRatingService;
	}

	public void execute() {
    	while(true){
    		Long sleepMillis = 2L*60*1000;
    			
    		String userSql = " select t1.id as user_id from "+BeanUser.class.getAnnotation(Table.class).name()+" t1 left join "+BeanCreditRating.class.getAnnotation(Table.class).name()+" t2 on (t1.credit_rating_id=t2.id) where t2.id is null or (t1.creditScore>t2.scoreIntervalUpper or t1.creditScore<t2.scoreIntervalLower)";
    		List<Object> userIdObjects = creditRatingService.findBySql(userSql);
    		
			for(Object userId : userIdObjects){
				creditRatingService.updateUser(((BigInteger)userId).longValue());
			}
			
			String shopSql = " select t1.id as shop_id from "+BeanShop.class.getAnnotation(Table.class).name()+" t1 left join "+BeanCreditRating.class.getAnnotation(Table.class).name()+" t2 on (t1.credit_rating_id=t2.id) where t2.id is null or (t1.creditScore>t2.scoreIntervalUpper or t1.creditScore<t2.scoreIntervalLower)";
    		List<Object> shopIdObjects = creditRatingService.findBySql(shopSql);
    		
			for(Object shopId : shopIdObjects){
				creditRatingService.updateShop(((BigInteger)shopId).longValue());
			}
			
    		try {
    			//睡眠时间
				Thread.sleep(sleepMillis);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    }
}
